<template>
  <div>
    <!-- <h1 class="mb-2">商品分类</h1> -->
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row class="mb-2">
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        class="mb-2"
        :data="catelist"
        row-key="id"
        default-expand-all
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="label" label="分类名称"> </el-table-column>
        <el-table-column prop="operation" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="50%" @close="addCateDialogClosed">
      <!-- 添加分类的表单 -->
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addCateForm.name"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="addCateForm.sort" type="number" :min="0" style="width:230px">
            <template slot="append">数值越小越靠前</template>
          </el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="p_value">
          <el-select v-model="addCateForm.p_value" @change="addDialogChange" clearable placeholder="请选择">
            <el-option v-for="item in parentCateList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类名称的对话框 -->
    <el-dialog title="修改分类名称" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="editForm.sort" type="number" :min="0" style="width:230px">
            <template slot="append">数值越小越靠前</template>
          </el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="p_value">
          <el-select v-model="editForm.p_value" @change="editDialogChange" clearable placeholder="请选择">
            <el-option v-for="item in parentCateList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateName">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import GetCateList from "@/utils/productCate";

export default {
  data() {
    return {
      // 商品分类的数据列表，默认为空
      catelist: [
        // {
        //   id: 1,
        //   label: "音符业务",
        //   children: [
        //     { id: 11, label: "音符上榜业务" },
        //     { id: 12, label: "音符不上榜业务" },
        //   ],
        // }
      ],
      // 控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      // 添加分类的表单数据对象
      addCateForm: {
        // 数值越小越靠前
        sort: 100,
        // 将要添加的分类的名称
        name: "",
        // 选中的父级分类的值
        p_value: "",
      },
      // 添加分类表单的验证规则对象
      addCateFormRules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
      },
      // 父级分类的列表
      parentCateList: [],
      // 控制修改分类名称对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的分类名称对象
      editForm: {
        id: "",
        // 数值越小越靠前
        sort: 100,
        name: "",
        item: "", // 当前对象信息
        // 选中的父级分类的值和id
        p_value: "",
        p_id: "",
      },
      // 修改分类表单的验证规则对象
      editFormRules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getCateList();
    this.$store.commit("changeBreadcrumb", this.$route);
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const parentList = await GetCateList();
      parentList.forEach((item) => {
        item.children && item.children.length != 0 && item.children.sort((a, b) => a.sort - b.sort);
      });
      this.catelist = this.parentCateList = parentList.sort((a, b) => a.sort - b.sort);
    },
    // 点击按钮，展示添加分类的对话框
    showAddCateDialog() {
      this.addCateDialogVisible = true;
    },
    // 点击按钮，添加新的分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const opt = this.addCateForm;
        // console.log(opt.p_value, 223);
        let isLeaf = opt.p_value ? 1 : 0;
        const formData = new FormData();
        formData.append("info_name", opt.name);
        formData.append("info_status", 0);
        formData.append("sort", opt.sort);
        formData.append("isLeaf", isLeaf);
        formData.append("parent_id", opt.p_value);
        const { data: res } = await this.$http.post("saveProductCategory", formData);
        // console.log(res);
        if (res.code != 0) {
          return this.$message.error("添加分类失败！");
        }
        this.$message.success("添加分类成功！");
        this.getCateList();
        this.addCateDialogVisible = false;
      });
    },
    // 添加对话框的事件改变函数
    addDialogChange(value) {
      // console.log(value);
      this.addCateForm.p_value = value;
    },
    // 修改对话框的事件改变函数
    editDialogChange(value) {
      // console.log(value);
      this.editForm.p_id = value;
    },
    // 监听对话框的关闭事件，重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
    },
    // 展示编辑分类名称的对话框
    showEditDialog(row) {
      // console.log(JSON.stringify(row));
      // console.log(row, "当前项");
      if (row.parent_id || row.children.length == 0) {
        // 此时为子级或者新添加的分类项
        this.parentCateList = this.catelist.filter((item) => item.id != row.id);
        // console.log(JSON.stringify(this.parentCateList), "父级");
      } else {
        // 此时为有子级的父级
        this.parentCateList = [];
      }
      this.editForm.id = row.id;
      this.editForm.sort = row.sort;
      this.editForm.name = row.label;
      this.editForm.item = row;
      this.editForm.p_value = row.parent_value || "";
      this.editForm.p_id = row.parent_id || "";
      // console.log(this.editForm, "33");
      this.editDialogVisible = true;
    },
    // 关闭修改分类名称对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 修改分类信息并提交
    editCateName() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const opt = this.editForm;
        let isLeaf = opt.p_value ? 1 : 0;
        const formData = new FormData();
        formData.append("id", opt.id);
        formData.append("info_name", opt.name);
        formData.append("info_status", 0);
        formData.append("sort", opt.sort);
        formData.append("isLeaf", isLeaf);
        formData.append("parent_id", opt.p_id);
        // 发起分类名称的数据请求
        const { data: res } = await this.$http.post("editProductCategory", formData);
        // console.log(res);

        if (res.code != "0") {
          return this.$message.error("更新分类名称失败！");
        }
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getCateList();
        // 提示修改成功
        this.$message.success("更新分类名称成功！");
      });
    },
    // 根据id删除对应的分类信息
    async removeUserById(row) {
      //弹框询问用户是否删除数据
      const confirmResult = await this.$confirm("此操作将永久删除该分类 , 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      //console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message("已取消删除");
      }
      // console.log(row);
      const delIDarr = [];
      if (row.parent_id) {
        delIDarr.push(row.id);
      } else {
        delIDarr.push(row.id);
        row.children.forEach((item) => {
          delIDarr.push(item.id);
        });
      }
      const formData = new FormData();
      formData.append("ids", delIDarr);
      const { data: res } = await this.$http.post("delProductCategory", formData);
      // console.log(res);
      if (res.code != "0") {
        return this.$message.error("删除分类失败！");
      }
      this.$message.success("删除分类成功！");
      this.getCateList();
    },
  },
};
</script>

<style lang="scss">
.el-cascader {
  width: 100%;
}
</style>
